﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Windows.Forms;

namespace InfoSender
{
   public partial class MainForm : Form
   {
      private const int defaultTimeout = 1800;
      private static List<string> IPs = new List<string>();
      
      public MainForm()
      {
         InitializeComponent();
         timer1_Tick(timer1, EventArgs.Empty);
         timer1.Enabled = true;
      }

      private void timer1_Tick(object sender, EventArgs e)
      {
         infoPanel.Text += DateTime.Now.ToString() + '\n';
         
         try
         {
            //Prepare email message
            MailMessage mailMessage = new MailMessage();
            mailMessage.From = new MailAddress("danild1984@mail.ru");
            mailMessage.Subject = string.Format("{0} {1}", 
                                                DateTime.Now.ToShortDateString(), 
                                                DateTime.Now.ToShortTimeString());
            mailMessage.Body = GetSystemInfo();

            if (mailMessage.Body != string.Empty)
            {
               infoPanel.Text += "Сообщение:\n" + mailMessage.Body + '\n';

               //Send email message
               SmtpClient smtpClient = new SmtpClient("smtp.mail.ru");
               smtpClient.UseDefaultCredentials = false;
               smtpClient.Credentials = new NetworkCredential("danild1984", "ppyR72");

               foreach (string email in GetEmails())
               {
                  mailMessage.To.Clear();
                  mailMessage.To.Add(email);
                  smtpClient.Send(mailMessage);
               }

               timer1.Interval = GetTimeout();
               infoPanel.Text += "Cообщение отправлено\n\n";
            }
            else
            {
               timer1.Interval = GetTimeout();
               infoPanel.Text += "Настройки не изменились\n\n";
            }
         }
         catch
         {
            timer1.Interval = 60 * 1000;
            infoPanel.Text += "Ошибка при отправке сообщения\n\n";
         }
      }

      private static string GetSystemInfo()
      {
         IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName());
         
         List<string> ipAddresses = new List<string>();
         foreach (IPAddress ipAddress in addresses)
         {
            byte[] bytes = ipAddress.GetAddressBytes();
            ipAddresses.Add(string.Format("{0}.{1}.{2}.{3}\n", bytes[0], bytes[1], bytes[2], bytes[3]));
         }

         foreach (string address in ipAddresses)
         {
            if (!IPs.Exists(delegate(string match) { return match == address; }))
            {
               IPs = ipAddresses;
               return string.Join("\n", ipAddresses.ToArray()) + '\n' + GetDrivesInfo();
            }
         }

         return string.Empty;
      }

      private static string GetDrivesInfo()
      {
         string drivesInfoText = string.Empty;
         DriveInfo[] drivesInfo = DriveInfo.GetDrives();
         foreach (DriveInfo driveInfo in drivesInfo)
         {
            if (driveInfo.DriveType == DriveType.Fixed)
            {
               drivesInfoText += string.Format("{0} - {1:F2}Mb\n", driveInfo.Name, (double)driveInfo.TotalFreeSpace / 1024 / 1024);
            }
         }
         return drivesInfoText.TrimEnd('\n');
      }

      private int GetTimeout()
      {
         string configValue = ConfigurationManager.AppSettings["Timeout"];
         int timeout;
         if (!int.TryParse(configValue, out timeout))
         {
            timeout = defaultTimeout;
         }
         return timeout * 1000;
      }
      
      private string[] GetEmails()
      {
         string configValue = ConfigurationManager.AppSettings["EmailTo"];
         string[] emails = configValue.Split(new char[] {',', ' '}, StringSplitOptions.RemoveEmptyEntries);
         return emails;
      }

      private void MainForm_Resize(object sender, EventArgs e)
      {
         if (WindowState == FormWindowState.Minimized)
         {
            Hide();
            notifyIcon1.Visible = true;
            ShowInTaskbar = false;
         }
      }

      private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
      {
         Show();
         WindowState = FormWindowState.Normal;
         notifyIcon1.Visible = false;
         ShowInTaskbar = true;
      }
   }
}